import { Topic } from '../../models/Topic'

export default defineEventHandler(async (event) => {
  const method = getMethod(event)
  const id = getRouterParam(event, 'id')
  
  // 获取单个题目
  if (method === 'GET') {
    try {
      const topic = await Topic.findById(id)
      if (!topic) {
        throw createError({
          statusCode: 404,
          message: '题目不存在'
        })
      }
      return topic
    } catch (error) {
      throw createError({
        statusCode: 500,
        message: '获取题目失败'
      })
    }
  }
  
  // 更新题目
  if (method === 'PUT') {
    try {
      const body = await readBody(event)
      const topic = await Topic.findByIdAndUpdate(id, body, { new: true })
      if (!topic) {
        throw createError({
          statusCode: 404,
          message: '题目不存在'
        })
      }
      return topic
    } catch (error) {
      throw createError({
        statusCode: 400,
        message: '更新题目失败'
      })
    }
  }
  
  // 删除题目
  if (method === 'DELETE') {
    try {
      const topic = await Topic.findByIdAndDelete(id)
      if (!topic) {
        throw createError({
          statusCode: 404,
          message: '题目不存在'
        })
      }
      return { message: '删除成功' }
    } catch (error) {
      throw createError({
        statusCode: 500,
        message: '删除题目失败'
      })
    }
  }
})